#include "tcpserver.h"
#include "ui_tcpserver.h"
#include<QTcpServer>
#include<QTcpSocket>
#include <synchapi.h>
Tcpserver::Tcpserver(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Tcpserver)
{
    ui->setupUi(this);
    ui->textEdit->setReadOnly(true);
    ui->textEdit->setTextInteractionFlags(Qt::NoTextInteraction);
    ui->textEdit->viewport()->setCursor(Qt::ArrowCursor);
    QString localIP = getLocalIP();
    ui->comboBox->addItem(localIP);
    tcpServer = new QTcpServer(this);
    connect(tcpServer, SIGNAL(newConnection()), this, SLOT(do_newConnection()));
    ui->spinBox->setValue(666);
}

Tcpserver::~Tcpserver()
{
    if (tcpSocket != nullptr)
    {
        if (tcpSocket->state() == QAbstractSocket::ConnectedState)
            tcpSocket->disconnectFromHost();
    }
    if (tcpServer->isListening())
        tcpServer->close();
    delete ui;
}
void Tcpserver::do_connect()
{
    QMetaObject::invokeMethod(ui->pushButton, "clicked", Qt::QueuedConnection);
    emit success();
}
QString Tcpserver::getLocalIP()
{
    QString hostName = QHostInfo::localHostName();
    QHostInfo hostInfo = QHostInfo::fromName(hostName);
    QString localIP = "";
    QList<QHostAddress> addrList = hostInfo.addresses();
    if (addrList.isEmpty())
        return localIP;
    foreach (QHostAddress aHost, addrList)
        if (QAbstractSocket::IPv4Protocol == aHost.protocol())
        {
            localIP = aHost.toString();
            break;
        }
    return localIP;
}
void Tcpserver::do_newConnection()
{
    tcpSocket = tcpServer->nextPendingConnection();
    connect(tcpSocket, SIGNAL(connected()), this, SLOT(do_clientConnected()));
    do_clientConnected();
    connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(do_clientDisconnected()));
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(do_socketReadyRead()));
}
void Tcpserver::do_clientConnected()
{
    ui->textEdit->append("**client socket connected");
    ui->textEdit->append("**peer address:" + tcpSocket->peerAddress().toString());
    ui->textEdit->append("**peer port:" + QString::number(tcpSocket->peerPort()));
}
void Tcpserver::do_clientDisconnected()
{

    ui->textEdit->append("**client socket disconnected");
    tcpSocket->deleteLater();
}
void Tcpserver::do_socketReadyRead()
{
    while (tcpSocket->canReadLine())
        ui->textEdit->append("[in] " + tcpSocket->readLine());
}

void Tcpserver::on_pushButton_clicked()
{
    QString IP = ui->comboBox->currentText();
    quint16 port = ui->spinBox->value();
    QHostAddress address(IP);
    tcpServer->listen(address, port);
    ui->textEdit->append("**开始监听...");
    ui->textEdit->append("**服务器地址：" + tcpServer->serverAddress().toString());
    ui->textEdit->append("**服务器端口：" + QString::number(tcpServer->serverPort()));
}
void Tcpserver::on_pushButton_4_clicked()
{
    if (tcpServer->isListening())
    {
        if (tcpSocket != nullptr)
            if (tcpSocket->state() == QAbstractSocket::ConnectedState)
                tcpSocket->disconnectFromHost();

        tcpServer->close();
    }
}
void Tcpserver::on_pushButton_3_clicked()
{
    QString msg = ui->lineEdit->text();
    ui->textEdit->append("[out] " + msg);
    ui->lineEdit->clear();
    ui->lineEdit->setFocus();
    QByteArray str = msg.toUtf8();
    str.append('\n');
    tcpSocket->write(str);
}
void Tcpserver::on_pushButton_2_clicked()
{
    ui->textEdit->clear();
}

